package readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: javase
 * @description: 读写锁 ReentrantReadWriteLock 更加细粒度的锁
 *               共享锁（读锁）
 *              排它锁独占锁（写锁）
 * @author: lld
 * @create: 2021-04-18 20:33
 **/
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        MyCache myCache = new MyCache();
//        写入
        for (int i = 1; i <=5; i++) {
            final int num=i;
            new Thread(()->{
                myCache.put(num+"",num+"1");
            },String.valueOf(num)).start();
        }
        TimeUnit.SECONDS.sleep(1);
        //        读取
        for (int i = 1; i <=5; i++) {
            final int num=i;
            new Thread(()->{
                myCache.get(num+"");
            },String.valueOf(num)).start();
        }
    }
}
//我的缓存
class MyCache{
    private volatile Map<String,Object> map=new HashMap<>();
    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"数据+++");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"添加OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"获取---");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"获取OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
